package com.example.medicinetime;

import static android.app.AlarmManager.INTERVAL_DAY;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;



public class InputActivity extends AppCompatActivity {
    public static final String TAG="InputActivity";
    Calendar calendar= Calendar.getInstance(Locale.CHINA);


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_input);
        TextView today = (TextView) findViewById(R.id.medicien_startTime_show);
        TextView hour = (TextView) findViewById(R.id.medicien_dailyTime_show);

        //获取系统当前时间
        Date now = Calendar.getInstance().getTime();
        SimpleDateFormat sdf_date = new SimpleDateFormat("yyyy-MM-dd");
        final String todayStr=sdf_date.format(now);
        Log.i(TAG, "onCreate: now="+todayStr);
        today.setText(todayStr);

        SimpleDateFormat sdf_time = new SimpleDateFormat("HH:mm");
        final String nowStr=sdf_time.format(now);
        hour.setText(nowStr);



    }

    //设置服药开始日期
    public void datePick(View v){
        Log.i(TAG, "datePick: 日期选择");
        TextView date_picked=(TextView) findViewById(R.id.medicien_startTime_show);
        showDatePickerDialog(this,  4, date_picked, calendar);
    }

    //设置服药时间
    public void timePick(View v){
        Log.i(TAG, "timePick: 时间选择");
        TextView time_pick = (TextView) findViewById(R.id.medicien_dailyTime_show);
        showTimePickerDialog(this,  2, time_pick, calendar);
    }

    //提交提醒记录
    public void recordSubmit(View v) throws ParseException {
        Log.i(TAG, "recordSubmit: ");
        //添加药物名称
        EditText medecien_name_edit = (EditText) findViewById(R.id.input_medicien_name);
        String medecien_name =medecien_name_edit.getText().toString();
        //获取开始服药日期
        TextView start_time_edit = (TextView) findViewById(R.id.medicien_startTime_show);
        String start_time =start_time_edit.getText().toString();
        //获取服药天数
        EditText duration_edit = (EditText) findViewById(R.id.input_duration);
        String medecien_duration_str =duration_edit.getText().toString();
        //获取服药时间
        TextView day_time_edit = (TextView) findViewById(R.id.medicien_dailyTime_show);
        String day_time =day_time_edit.getText().toString();
        //获取服药剂量
        EditText dosis_edit = (EditText) findViewById(R.id.input_dosis);
        String medecien_dosis_str =dosis_edit.getText().toString();


        //不合法输入判断
        if(medecien_name.equals("")||start_time.equals("")||medecien_duration_str.equals("")||day_time.equals("")||medecien_dosis_str.equals("")){
            Toast.makeText(InputActivity.this, R.string.input_invalid_tip, Toast.LENGTH_SHORT).show();
        }
        else{
            MedicienRecord medicienRecord = new MedicienRecord();
            //添加药物名称
            medicienRecord.setMedicienName(medecien_name);
            Log.i(TAG, "recordSubmit: medecien_name"+medecien_name);
            //添加开始服药日期
            medicienRecord.setStartTime(start_time);
            Log.i(TAG, "recordSubmit: start_time="+start_time);
            //添加服药天数
            int medecien_duration = Integer.parseInt(medecien_duration_str);
            medicienRecord.setDuration(medecien_duration);
            Log.i(TAG, "recordSubmit: medecien_duration"+medecien_duration);

            //针对不同天数设置定时闹钟
            int alarmId;
            Intent myIntent = new Intent();
            myIntent.setAction("VIDEO_TIMER");
            SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd HH:mm" );
            String notice_time_str = start_time+" "+day_time;
            Date notice_time = sdf.parse(notice_time_str);
            if(medecien_duration>1){
                //设置重复闹钟
                Log.i(TAG, "recordSubmit: 设置重复闹钟");
                int alarmID = Alarm.setRepeatingAlarmTimer(this,notice_time.getTime(),24*360*1000,"VIDEO_TIMER",AlarmManager.RTC_WAKEUP);
                medicienRecord.setAlarmId(alarmID);
            }else{
                //设置单次闹钟
                Log.i(TAG, "recordSubmit: 设置单次闹钟");
                int alarmID = Alarm.setAlarmTimer(this,notice_time.getTime(),"VIDEO_TIMER",AlarmManager.RTC_WAKEUP);
                medicienRecord.setAlarmId(alarmID);
            }

            //添加服药时间
            medicienRecord.setDailytime(day_time);
            Log.i(TAG, "recordSubmit: day_time="+day_time);
            //添加服药剂量
            int medecien_dosis = Integer.parseInt(medecien_dosis_str);
            medicienRecord.setDosis(medecien_dosis);
            Log.i(TAG, "recordSubmit: medecien_dosis"+medecien_dosis);

            //添加记录如数据库
            DBManager dbManager = new DBManager(InputActivity.this);
            dbManager.add(medicienRecord);

            submit_suc_toast();

            Intent index_intent = new Intent(this, MainActivity.class);
            startActivity(index_intent);
        }

    }

    //显示提交成功
    //https://blog.csdn.net/qq_28301007/article/details/52335360
    private void submit_suc_toast() {
        //图片Toast
        Toast toast=Toast.makeText(getApplicationContext(), R.string.submit_success, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        //创建图片视图对象
        ImageView imageView= new ImageView(getApplicationContext());
        //设置图片
        imageView.setImageResource(R.drawable.submit_success);
        imageView.setBackgroundColor(1);
        //获得toast的布局
        LinearLayout toastView = (LinearLayout) toast.getView();
        //设置此布局为横向的
        toastView.setOrientation(LinearLayout.VERTICAL);
        //将ImageView在加入到此布局中的第一个位置
        toastView.addView(imageView, 0);
        toast.show();
    }

    /**
     * 日期选择
     * https://blog.csdn.net/ceaningking/article/details/89916700
     * @param activity
     * @param themeResId
     * @param tv
     * @param calendar
     */
    public static void showDatePickerDialog(Activity activity, int themeResId, final TextView tv, Calendar calendar) {
        // 直接创建一个DatePickerDialog对话框实例，并将它显示出来
        new DatePickerDialog(activity, themeResId, new DatePickerDialog.OnDateSetListener() {
            // 绑定监听器(How the parent is notified that the date is set.)
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // 此处得到选择的时间，可以进行你想要的操作
                tv.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            }
        }
                // 设置初始日期
                , calendar.get(Calendar.YEAR)
                , calendar.get(Calendar.MONTH)
                , calendar.get(Calendar.DAY_OF_MONTH)).show();
    }

    /**
     * 时间选择
     * https://blog.csdn.net/ceaningking/article/details/89916700
     * @param activity
     * @param themeResId
     * @param tv
     * @param calendar
     */
    public static void showTimePickerDialog(Activity activity,int themeResId, final TextView tv, Calendar calendar) {
        // Calendar c = Calendar.getInstance();
        // 创建一个TimePickerDialog实例，并把它显示出来
        // 解释一哈，Activity是context的子类
        new TimePickerDialog( activity,themeResId,
                // 绑定监听器
                new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        if(minute<10){
                            tv.setText(hourOfDay + ":0"+minute);
                        }else{
                            tv.setText(hourOfDay + ":" + minute);
                        }

                    }
                }
                // 设置初始时间
                , calendar.get(Calendar.HOUR_OF_DAY)
                , calendar.get(Calendar.MINUTE)
                // true表示采用24小时制
                ,true).show();
    }


}